package com.lmt.ymcc.comsumer;

import com.alibaba.fastjson.JSON;
import com.lmt.ymcc.constant.MessageConstant;
import com.lmt.ymcc.domain.MessageEmail;
import com.lmt.ymcc.dto.EmailSend2MQ;
import com.lmt.ymcc.exception.GlobalException;
import com.lmt.ymcc.service.IMessageEmailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

@Component
@RocketMQMessageListener(consumerGroup = "service-common-emailmessage-consumer",
        //Topic
        topic = MessageConstant.COURSE_MESSAGE_TOPIC,
         //TAGS
        selectorExpression = MessageConstant.COURSE_MESSAGE_TAG_EMAIL
)
@Slf4j
public class EmailMessageMQConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageEmailService messageEmailService;

    @Override
    public void onMessage(MessageExt message) {

        try {
            String bodyStr = new String(message.getBody(),"utf-8");
            EmailSend2MQ vo = JSON.parseObject(bodyStr, EmailSend2MQ.class);
            //1.保持数据到数据库
            MessageEmail messageEmail = new MessageEmail();
            BeanUtils.copyProperties(vo, messageEmail);
            messageEmailService.insert(messageEmail);
            //2.发送邮件
            log.info("给用户发送了推送短信");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            //通过异常来决定ACK
            throw new GlobalException("邮件发送失败");
        }
    }
}